package com.raising.modules.dic.utils;

import com.google.common.collect.Lists;
import com.raising.framework.spring.SpringUtils;
import com.raising.modules.dic.dao.DicRegionDao;
import com.raising.modules.dic.entity.DicRegion;
import com.raising.utils.JCacheUtils;
import com.raising.utils.JStringUtils;

import java.util.List;

/**
 * 行政区划字典工具类
 * @author GaoYuan
 * @datetime 2018/1/15 下午3:17
 */
public class RegionUtil {

    private static DicRegionDao dicRegionDao = SpringUtils.getBean(DicRegionDao.class);

    public static final String SYS_CACHE_DIC_REGION = "SYS_CACHE_DIC_REGION";

    /**
     * 获取所有城市（根据级别查询当前级别城市）
     * @param level 级别（1、2、3、null）
     * @author GaoYuan
     * @datetime 2018/1/15 下午3:07
     */
    public static List<DicRegion> getAllRegionList(String level) {
        List<DicRegion> regionList = (List<DicRegion>) JCacheUtils.get(SYS_CACHE_DIC_REGION);
        if (regionList == null) {
            regionList =  dicRegionDao.getList(null);
            JCacheUtils.put(SYS_CACHE_DIC_REGION, regionList);
        }
        if (regionList == null) {
            regionList = Lists.newArrayList();
        }
        if(JStringUtils.isNotBlank(level)){
            List<DicRegion> regionList_new = Lists.newArrayList();
            for(DicRegion dicRegion:regionList){
                if(level.equals(dicRegion.getLevel())){
                    regionList_new.add(dicRegion);
                }
            }
            return regionList_new;
        }
        return regionList;
    }

    /**
     * 根据cd或id查询下级城市
     * @author GaoYuan
     * @param regionCd 选择的目标城市id或cd
     * @datetime 2018/1/15 下午3:16
     */
    public static List<DicRegion> getRegionChildByCd(String regionCd){
        if(JStringUtils.isNotBlank(regionCd)){
            List<DicRegion> regionList = getAllRegionList(null);
            List<DicRegion> regionList_new = Lists.newArrayList();
            for(DicRegion dicRegion:regionList){
                if(regionCd.equals(dicRegion.getParentId())){
                    regionList_new.add(dicRegion);
                }
            }
            return regionList_new;
        }else{
            return Lists.newArrayList();
        }
    }

    /**
     * 清空缓存
     * @author GaoYuan
     * @datetime 2018/1/15 下午3:19
     */
    public static void removeCache(){
        JCacheUtils.put(SYS_CACHE_DIC_REGION, null);
    }

}
